package com.example.treehole.ui.page.login

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.component.isValidEmail
import com.example.treehole.ui.component.passwordFilter
import com.example.treehole.ui.component.showLoginSnackbar
import com.example.treehole.ui.model.InputCardType
import com.example.treehole.ui.theme.Cyan
import com.example.treehole.ui.theme.darkCyan
import kotlinx.coroutines.launch

@Composable
fun InputCard(
    inputValue: String,
    inputCardType: InputCardType,
    passWord: String = "",
    changePassword: Boolean = false,
    onInputValueChange: (String) -> Unit,
    onErrorMessageChange: (String) -> Unit
) {
    val loginViewModel = LocalLoginViewModel.current
    val inputEmail by loginViewModel.inputEmail.collectAsState()
    val scope = rememberCoroutineScope()

    val label = when (inputCardType) {
        InputCardType.EMAIL -> "输入邮箱"
        InputCardType.PASSWORD -> if (changePassword) "输入新密码" else "输入密码"
        InputCardType.VERIFY_CODE -> "输入六位验证码"
        InputCardType.PASSWORD_AGAIN -> if (changePassword) "再次输入新密码" else "再次输入密码"
    }
    var showPassword by remember { mutableStateOf(false) }
    val countDown: VerifyCodeViewModel = viewModel()
    val countDownTime = countDown.countDownTime.intValue
    val isSendingCode = countDown.isSendingCode.value

    TextField(
        value = inputValue,
        onValueChange = { newText ->
            when (inputCardType) {
                InputCardType.EMAIL -> onInputValueChange(newText)
                InputCardType.PASSWORD -> {
                    val allowedCharacters = passwordFilter(newText)
                    if (newText.length != allowedCharacters.length) {
                        onErrorMessageChange("密码只能包含字母、数字以及!@#$%^&*")
                    } else if (newText.length > 20) {
                        onErrorMessageChange("密码长度不能超过20")
                    } else {
                        onErrorMessageChange("")
                    }
                    onInputValueChange(newText)
                }

                InputCardType.PASSWORD_AGAIN -> onInputValueChange(newText)
                InputCardType.VERIFY_CODE -> {
                    val allowedCharacters = newText.filter { it.isDigit() }
                    if (newText.length != allowedCharacters.length) onErrorMessageChange("验证码只能包含数字")
                    else onErrorMessageChange("")
                    onInputValueChange(newText)
                }
            }
        },
        label = { Text(label) },
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp)
            .background(
                brush = Brush.horizontalGradient(
                    colors = listOf(darkCyan, Cyan),
                ),
                shape = RoundedCornerShape(8.dp)
            )
            .onFocusChanged { focusState ->
                if (!focusState.isFocused) {
                    if (inputCardType == InputCardType.EMAIL) {
                        if (inputValue.isNotEmpty() && !isValidEmail(inputValue)) {
                            onErrorMessageChange("请输入有效的邮箱")
                        } else{
                            onErrorMessageChange("")
                        }
                    } else if (inputCardType == InputCardType.PASSWORD_AGAIN) {
                        if (inputValue.isNotEmpty() && inputValue != passWord) {
                            onErrorMessageChange("两次输入密码不相同")
                        } else {
                            onErrorMessageChange("")
                        }
                    } else if (inputCardType == InputCardType.VERIFY_CODE) {
                        if (inputValue.isNotEmpty() && inputValue.length != 6) {
                            onErrorMessageChange("验证码是6位")
                        } else {
                            onErrorMessageChange("")
                        }
                    }
                }

            },
        colors = TextFieldDefaults.colors(
            focusedContainerColor = Color.Transparent,
            unfocusedContainerColor = Color.Transparent,
            disabledContainerColor = Color.Transparent,
            focusedIndicatorColor = Color.Transparent,
            unfocusedIndicatorColor = Color.Transparent,
            disabledIndicatorColor = Color.Transparent
        ),
        visualTransformation = if (
            inputCardType == InputCardType.EMAIL
            || inputCardType == InputCardType.VERIFY_CODE
            || showPassword
        ) VisualTransformation.None
        else PasswordVisualTransformation(),
        trailingIcon = {
            if (inputCardType == InputCardType.PASSWORD || inputCardType == InputCardType.PASSWORD_AGAIN) {
                IconButton(onClick = { showPassword = !showPassword }) {
                    Icon(
                        imageVector = if (showPassword) Icons.Default.Visibility else Icons.Default.VisibilityOff,
                        contentDescription = if (showPassword) "隐藏密码" else "显示密码"
                    )
                }
            } else if (inputCardType == InputCardType.VERIFY_CODE) {
                Button(
                    modifier = Modifier
                        .padding(horizontal = 4.dp)
                        .width(120.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = darkCyan,
                        disabledContainerColor = Color.Gray
                    ),
                    onClick = {
                        scope.launch {
                            if (isValidEmail(inputEmail)) {
//                                Log.d("VerifyCode","here")
                                if (DataRepository.sendVerifyCode(inputEmail))
                                    countDown.startCountDown() // 启动倒计时
                            } else {
                                showLoginSnackbar("请输入有效邮箱")
                            }
                        }
                    },
                    enabled = !isSendingCode
                ) {
                    Text(if (isSendingCode) "${countDownTime}s" else "发送验证码")
                }
            }
        },
        singleLine = true
    )

}